package com.wanchuang.qhbb;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;

import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.wanchuang.qhbb.base.BaseActivity;
import com.wanchuang.qhbb.base.MainApplication;
import com.wanchuang.qhbb.dialog.ActionDialog;
import com.wanchuang.qhbb.module.main.HomeFragment;
import com.wanchuang.qhbb.module.mine.MineFragment;
import com.wanchuang.qhbb.net.Apis;
import com.wanchuang.qhbb.net.NetworkManager;
import com.wanchuang.qhbb.net.WebApis;
import com.wanchuang.qhbb.net.interfaces.OnRequestCallBack;
import com.wanchuang.qhbb.net.interfaces.OnUpLoadCallBack;
import com.wanchuang.qhbb.proto.Index;
import com.wanchuang.qhbb.proto.MemberOuterClass;
import com.wanchuang.qhbb.utils.APKVersionCodeUtils;
import com.wanchuang.qhbb.utils.StatusBarUtil;
import com.wanchuang.qhbb.utils.updateutil.UpdateManager;
import com.wanchuang.qhbb.view.NoScrollViewPager;
import com.wanchuang.qhbb.web.ui.WebViewFragment;
import com.google.android.material.tabs.TabLayout;
import com.google.protobuf.InvalidProtocolBufferException;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import kale.ui.view.dialog.EasyDialog;

public class MainActivity extends BaseActivity {

    @BindView(R.id.viewPagers)
    NoScrollViewPager viewPager;
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;


    private long mExitTime;
    public String tureeName = "";
    private HomeFragment home;
    private int INSTALL_PERMISS_CODE = 10000;
    private MineFragment minefragment;
    private int clickTime = 0; // 点击次数
    private WebViewFragment statistics;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StatusBarUtil.setWhiteStatusBar(this);
        ButterKnife.bind(this);
        MainApplication.addTempActivity(this);
        initMenus();
        initView();
        checkVersion();
        showAlert();
    }


    String[] tabNames;
    int[] tabIcons;

    private void initMenus() {
        tabNames = getResources().getStringArray(R.array.main_tabs);
        TypedArray ar = getResources().obtainTypedArray(R.array.main_tab_icons);
        int len = ar.length();
        tabIcons = new int[len];
        for (int i = 0; i < len; i++) {
            tabIcons[i] = ar.getResourceId(i, 0);
        }
        ar.recycle();
    }

    private void initView() {
        tureeName = getIntent().getStringExtra("trueName");
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(home = new HomeFragment());
        fragments.add(statistics = WebViewFragment.newInstance(MainApplication.getServiceHost() + WebApis.statistics));
        fragments.add(WebViewFragment.newInstance(MainApplication.getServiceHost() + WebApis.qrcode));
        fragments.add(minefragment = new MineFragment());
        viewPager.setOffscreenPageLimit(4);
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public int getCount() {
                return fragments.size();
            }

            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return null;
            }

        });
        //设置图标
        tabLayout.setupWithViewPager(viewPager);
        for (int i = 0; i < tabNames.length; i++) {
            tabLayout.getTabAt(i).setCustomView(getTabView(tabNames[i], tabIcons[i], i));
        }

        // 设置监听
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 0) {
                    home.onResume();
                }else if (tab.getPosition() == 1) {
                    if (clickTime == 0) {clickTime ++;} else {statistics.reLoad();}
                }

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });


    }

    public View getTabView(String tabName, int tabIcon, int position) {

        View view = LayoutInflater.from(mContext).inflate(R.layout.tab_layout, null);
        ImageView iv_tab = view.findViewById(R.id.iv_tab);
        TextView tv_tab = view.findViewById(R.id.tv_tab);
        iv_tab.setImageResource(tabIcon);
        tv_tab.setText(tabName);

        return view;
    }

    //返回
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
                getSupportFragmentManager().popBackStack();
                return true;
            }
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast.makeText(mContext, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                MainApplication.finishAllActivity();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void checkVersion() {
        Index.get_app_version_info.Builder builder = Index.get_app_version_info.newBuilder();
        builder.setClient("android");
        NetworkManager.INSTANCE.post(Apis.versionCode, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) {
                checkVerison(response);
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                hideProgress();
            }
        });

    }

    private void checkVerison(byte[] response) {
        String versionName = APKVersionCodeUtils.getVerName(mContext);
        Index.get_app_version_info versionBean = null;
        try {
            versionBean = Index.get_app_version_info.parseFrom(response);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
        Log.e("mango", "checkVerison: " + versionBean);
        // 改为匹配版本号
        float serviceVersion = Float.parseFloat(versionBean.getVersion());
        float locationeVersion = Float.parseFloat(versionName);
        if (locationeVersion < serviceVersion) {
            UpdateManager.getInstance()
                    .setContext(this)
                    .setFragmentManager(getSupportFragmentManager())
                    .setUrl(versionBean.getDownloadUrl())
                    .setIsforce(versionBean.getForce())
                    .setContent(versionBean.getContext())
                    .start();
        }
    }



    private void showAlert() {
        Index.get_agreement.Builder builder = Index.get_agreement.newBuilder();
        builder.setType("act_alert");
        NetworkManager.INSTANCE.post(Apis.get_agreement, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                Index.get_agreement agreement = Index.get_agreement.parseFrom(response);
                Log.e("mango", "onOk: " + agreement);
                if (agreement.getActState().equals("1")) {
                    ActionDialog.Builder builder = new ActionDialog.Builder(mContext);
                    builder.setContent(agreement.getContent());
                    EasyDialog build = builder.build();
                    build.show(getSupportFragmentManager());
                }
            }

            @Override
            public void onError(int errorCode, String errorMessage) {

            }
        });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    List<LocalMedia> localMedias = PictureSelector.obtainMultipleResult(data);
                    NetworkManager.INSTANCE.upLoadMultiFile(localMedias, new OnUpLoadCallBack() {
                        @Override
                        public void onOk(String response) {
                            MemberOuterClass.Member.Builder builder = MemberOuterClass.Member.newBuilder();
                            builder.setMemberAvatar(response);
                            NetworkManager.INSTANCE.post(Apis.editMemberDataInfo, builder.build().toByteArray(), new OnRequestCallBack() {//2.修改个人信息。
                                @Override
                                public void onOk(byte[] bytes) {


                                }

                                @Override
                                public void onError(int errorCode, String errorMessage) {

                                    if (errorCode == 200)
                                    {
                                        showToast(errorMessage); //服务器连接失败。
                                        minefragment.reloadHead(response);
                                    }

                                }
                            });
                        }


                        @Override
                        public void onError(int code, String errorMessage) {
                            showToast("上传失败");
                        }

                        @Override
                        public void upProgress(int progress) {

                        }
                    });


            }
        }
    }


}
